package com.yohann.algorithm;

/**
 * <p>
 * 稀疏数组
 * </p>
 *
 * @author Yohann
 * @since 2020/9/21
 */
public class SparseArrayTest {
    public static void main(String[] args) {
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;

        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.print(data+"  ");
            }
            System.out.println();
        }
        System.out.println("**************************************");

        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0){
                    sum++;
                }
            }
        }

        //创建稀疏数组
        int sparseArr[][] = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        //给稀疏素组赋值
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0){
                    sparseArr[i][0] = i;
                    sparseArr[i][1] = j;
                    sparseArr[i][2] = chessArr1[i][j];
                }
            }
        }

        for (int[] row : sparseArr) {
            for (int data : row) {
                System.out.print(data+"  ");
            }
            System.out.println();
        }
        System.out.println("**************************************");

        //稀疏数组复原
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];

        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }

        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.print(data+"  ");
            }
            System.out.println();
        }
        System.out.println("**************************************");
    }
}